﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using HandyControl.Controls;
using HandyControl.Data;
using QQPlcPlayer.ViewModel;
using QServices;
using RabbitMQ.Client.Events;
using RabbitMQ.Client;
using System.Threading.Channels;
using System.Windows.Interop;
using System.Text.Json;
using MQTTnet.Client;
using MQTTnet.Server;
using MQTTnet;
using Microsoft.Extensions.DependencyInjection;
using QServices.Services;
using QModels;
using Quartz;


namespace QQPlcPlayer
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : HandyControl.Controls.Window
	{



		//public static IMqttClient? m_mqttclient { get; set; } = null;
		public static bool IsUpdateCarStatus { get; set; }
		public static bool IsUpdateCarElectricLimit { get; set; }
		public static bool IsUpdateChongDianTask { get; set; }
		public static AgvCarUpdateCarElectricLimit AgvCarUpdateCarElectricLimit { get; set; }
		public async Task InitRabbitMQ()
		{

			var options = new MqttClientOptionsBuilder()
				.WithTcpServer(AppRuntime.Rabbitmq_ip, 1883)
				.WithCredentials(AppRuntime.Rabbitmq_user, AppRuntime.Rabbitmq_pwd)
				.WithKeepAlivePeriod(TimeSpan.FromSeconds(10))
				.Build();

			var factory = new MqttFactory();
			var m_mqttclient = factory.CreateMqttClient();

			await m_mqttclient.ConnectAsync(options);
			AppRuntime.m_mqttclient = m_mqttclient;
		}



		/// <summary>
		/// 1秒定时器
		/// </summary>
		private DispatcherTimer m_dispatcherTimer;

		public MainWindow()
		{
			InitializeComponent();
			AppRuntime.Init();
			//this.DataContext = new MainWindowViewModel();
			m_dispatcherTimer = new DispatcherTimer();
			m_dispatcherTimer.Tick += Main_dispatcherTimer_Tick;
			m_dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
			m_dispatcherTimer.Start();

			InitRabbitMQ();
			//SqliteDBHelper.InitDB_Table();

		
		}




		private void Window_Loaded(object sender, RoutedEventArgs e)
		{

			try
			{
				UpdateCarCurrentStatus(null);

			}
			catch (Exception ex)
			{
				Growl.ErrorGlobal(ex.Message);
			}
		}


		public CarStatus LastCarStatus { get; set; }
		private async void UpdateCarCurrentStatus(MainWindowViewModel vm)
		{
			try
			{
				if (vm == null) return;
				//获取当前电量
				var eleQty = AppRuntime.GetPlcManager().当前电量();

				if (vm == null && this.DataContext is MainWindowViewModel datacontext)
				{
					datacontext.CurrentElectricQty = eleQty;
				}
				if (vm != null)
				{
					vm.CurrentElectricQty = eleQty;
				}

				#region 处理电量
				var tt = AppRuntime.GetPlcManager().GetGVCarStatusModel();

				var carstatus = tt.ChongDian ? CarStatus.Charging : CarStatus.None;
				carstatus = tt.GuZhangQuanBu ? CarStatus.Trouble : carstatus;
				carstatus = tt.WeiLiaoZhong ? CarStatus.WeiLiao : carstatus;
				if (AppRuntime.IsNetworkAvailable())
				{

					var obj = new { CarNumber = AppRuntime.CarNumber, Qty = eleQty, TongXin = tt.TongXinOK, CarStatus = (int)carstatus };
					var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(obj));
					//RabbitMQChannel.ExchangeDeclare(exchange: "CarElectricQty", type: ExchangeType.Fanout, durable: true);
					var message = new MqttApplicationMessage
					{
						PayloadSegment = bytes,
						Topic = "CarElectricQty",
						QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce
					};
					try
					{
						if (!AppRuntime.m_mqttclient.IsConnected) await AppRuntime.m_mqttclient.ReconnectAsync();
						await AppRuntime.m_mqttclient.PublishAsync(message);

					}
					catch (Exception ex)
					{
						AppRuntime.Logger_Error("mqtt连接异常");
					}

					AppRuntime.GetService().GetService<AgvCarService>().UpdateAGVElEQty(new QModels.AgvCar { CarNumber = obj.CarNumber, Electricity = obj.Qty, CarStatus = carstatus });


				}

				if (carstatus != LastCarStatus && carstatus == CarStatus.Charging)
				{
					vm.ChongDianAlarm.StartAlarm();
				}
				LastCarStatus = carstatus;

				#endregion
			}
			catch (Exception ex)
			{
				var errinfo = new GrowlInfo
				{
					Message = "获取小车电量失败",

					IsCustom = true,

				};
				Growl.ErrorGlobal(errinfo);
				AppRuntime.Logger_Error(ex);
			}



		}


		private void Main_dispatcherTimer_Tick(object? sender, EventArgs e)
		{
			if (this.DataContext is MainWindowViewModel datacontext)
			{
				datacontext.NowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
				if (DateTime.Now.Second % 5 == 0) Task.Run(() => UpdateCarCurrentStatus(datacontext));
				CheckAutoFeed(datacontext);
				if (AppRuntime.IsUpdateUpdateCarStatus)
				{
					datacontext.ChongDianAlarm.IsStop=true;
					datacontext.FeedAlarm.IsStop=true;
					this.DataContext = new MainWindowViewModel();
					AppRuntime.IsUpdateUpdateCarStatus = false;
				}

				if (AppRuntime.IsUpdatePigeonCage)
				{
					Task.Run(() => datacontext.InitDataForPLC());
					AppRuntime.IsUpdatePigeonCage = false;
				}
				
			}
		}

		private void CheckAutoFeed(MainWindowViewModel vm)
		{

			if (!vm.IsCheckAuto) return;

			if (vm.m_autoTimer != null && vm.m_autoTimer.IsEnabled) return;


			if (DateTime.Now.Hour <= vm.HourFirst && DateTime.Now.Minute <= vm.MinuteFirst)
			{
				var timerspan = vm.first_Time - DateTime.Now;
				if (timerspan.TotalSeconds > 10) return;
				Growl.SuccessGlobal("第一次喂料马上开始!");
				AppRuntime.Logger_Info("第一次喂料马上开始!");
				if (vm.m_autoTimer == null || !vm.m_autoTimer.IsEnabled)
				{
					vm.InitAutoFeedTimer();
				}
				AppRuntime.FirstFeedCache.Clear();
			}
			else if (DateTime.Now.Hour <= vm.HourSecond && DateTime.Now.Minute <= vm.MinuteSecond)
			{
				var timerspan = vm.second_Time - DateTime.Now;
				if (timerspan.TotalSeconds > 10) return;
				Growl.SuccessGlobal("第二次喂料马上开始!");
				AppRuntime.Logger_Info("第二次喂料马上开始!");
				if (vm.m_autoTimer == null || !vm.m_autoTimer.IsEnabled)
				{
					vm.InitAutoFeedTimer();
				}
				AppRuntime.SecondFeedCache.Clear();
			}
			else if (DateTime.Now.Hour <= vm.HourThird && DateTime.Now.Minute <= vm.MinuteThird)
			{
				var timerspan = vm.third_Time - DateTime.Now;
				if (timerspan.TotalSeconds > 10) return;
				Growl.SuccessGlobal("第三次喂料马上开始!");
				AppRuntime.Logger_Info("第三次喂料马上开始!");
				if (vm.m_autoTimer == null || !vm.m_autoTimer.IsEnabled)
				{
					vm.InitAutoFeedTimer();
				}
				AppRuntime.ThirdFeedCache.Clear();
			}




		}

	}
}